#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include "api/api.h"

int main(int argc, char** argv)
{
	printf("Receiving transmission!\n");
	int port_fd = llopen(TTYS0, RECEIVER);
	char buf[DATA_SIZE];
	//TODO: mudar nome para nome do ficheiro
	//llread do primeiro pacote de inicio de transmissao
	int bytes_read = llread(port_fd, buf);
	//char filepath[DATA_SIZE] = "output/";
	//strcat(filepath,buf);
	//printf("file path: %s\n", filepath);
	int file_fd = open("output/derp", O_WRONLY | O_CREAT, 0740);
	bzero(buf,DATA_SIZE);
	printf("\ntransmission setup\n");
	while(bytes_read != 0)
	{
		bzero(buf,DATA_SIZE);
		bytes_read = llread(port_fd, buf);
		if (bytes_read == 0) //received final packet with no data
		{
			break;
		}
		else
		{
			int i;
			//for(i=0;i<bytes_read;i++)
			//	printf("rr: %x, %c\n",buf[i],buf[i]);
			printf("FFF: %s\n",buf);
			write(file_fd, buf, bytes_read);
		}
	}
	
	
	close(file_fd);
	int file_fdd = open("output/derp", O_RDWR);
	char buf_a[1];
	while(read(file_fdd,&buf_a,1) > 0)
		printf("D: %c; %x\n", buf_a[0],buf_a[0]);
	close(file_fdd);
	llclose(port_fd);
	
	printf("End of Receiver\n");
	
	return 0;
}

/*
int main(int argc, char** argv)
{
	int fd = llopen(TTYS0, RECEIVER);
	printf("llopen returned\n");

	//int dest_fd;
	int dest_fd = open("output/receivedfile", O_WRONLY | O_CREAT, 0740);

	int bytes_read = 1;
	int state = 0;
	int total_bytes = 0;
	char cc;
	
	printf("START READING FILE\n");
	while ( 1 )
	{

		bytes_read = read(fd, &cc, 1);
		printf("Read %d bytes \n", bytes_read);

		if (state == START_FILE) {
			if( interpret_packet(START_PACKET, &cc, &filesize, &filename) == 0 ) {
				strcat(filepath, filename);
				fd = open(filepath, O_WRONLY | O_CREAT, 0740);
				state++; 
				}
		}
		else if (state == TRANSFER_FILE) {
			total_bytes += bytes_read;
			printf("Progress: %d/%d \%", bytes_counter, file_size);
			if (total_bytes >= file_size) 
				state++;
		}
		else if (state == END_FILE) {
			if( interpret_packet(END_PACKET, &cc, &filesize) == 0 ) {
				break;
			}
		}
	
		if( cc == '0' ) {
			state++;
			write(dest_fd, &cc,1);
		}
		else {
			state = 0;
			write(dest_fd, &cc,1);
		}
		if (state == 3) {
			break;
		}
	}
	
	printf("file received\n");
	
	close(dest_fd);
	llclose(fd);
	
	return 0;
}
*/
